﻿using System;
using System.Collections.Generic;
using XCI.Helper;

namespace XCI.Core
{
    /// <summary>
    /// JsonMap配置文件
    /// </summary>
    public class JsonMapConfig
    {
        private Dictionary<string, object> data;

        /// <summary>
        /// 获取文件路径
        /// </summary>
        public string Path { get; private set; }

        /// <summary>
        /// 初始化实例
        /// </summary>
        public JsonMapConfig()
        {
        }

        /// <summary>
        /// 使用指定文件路径初始化实例
        /// </summary>
        /// <param name="path">文件路径</param>
        public JsonMapConfig(string path)
        {
            if (string.IsNullOrEmpty(path)) throw new ArgumentException("请指定配置文件路径", nameof(Path));
            this.Load(path);
        }

        /// <summary>
        /// 从指定文件中重新加载配置数据
        /// </summary>
        /// <param name="path">文件路径</param>
        public void Load(string path)
        {
            this.Path = path;
            this.Load();
        }

        /// <summary>
        /// 加载配置数据
        /// </summary>
        public void Load()
        {
            data = JsonHelper.FromJsonFile<Dictionary<string, object>>(Path) ?? new Dictionary<string, object>();
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        public void Save()
        {
            JsonHelper.ToJsonFile(Path, data);
        }

        /// <summary>
        /// 获取指定名称的配置对象
        /// </summary>
        /// <typeparam name="T">配置类型</typeparam>
        /// <param name="key">配置名称</param>
        /// <param name="defaultValue">如果未找到指定名称的配置对象时,返回此默认值</param>
        /// <returns>返回指定名称的配置对象</returns>
        public T Get<T>(string key, Func<T> defaultValue = null)
        {
            if (data.TryGetValue(key, out var value))
            {
                var result = JsonHelper.ToObject<T>(value);
                data[key] = result;
                return result;
            }

            if (defaultValue == null) return default(T);
            T dafValue = defaultValue.Invoke();
            data[key] = dafValue;
            return dafValue;
        }

        /// <summary>
        /// 设置指定名称的配置对象
        /// </summary>
        /// <typeparam name="T">配置类型</typeparam>
        /// <param name="key">配置名称</param>
        /// <param name="value">配置对象</param>
        public void Set<T>(string key, T value)
        {
            data[key] = value;
        }

    }
}